﻿using System;
using UnityEngine;
using System.Collections;
using System.IO;
using System.Net;
using System.Text;
using LitJson;
using UnityEngine.Networking;
using LuaInterface;

 public class LBSLocation : MonoBehaviour
{
    public static LBSLocation Instance=null;
    public static LuaFunction LBScall;

    public static String LBSConst="";

    public static LBSLocation GetInstance()
    {
        return Instance;
    }
    private void Awake()
    {
        Instance = this;
    }
    void Start()
    {
        //获取位置权限后移
        //StartCoroutine(StartLocation());
    }

    string FURL="https://api.map.baidu.com/reverse_geocoding/v3/?ak=SfrwGH7INvjPq7BwCrYrioBQZm9XXxrR&output=json&coordtype=wgs84ll&extensions_town=true&location={0},{1}";
    public static String GetLocationDataGPS() {
        return LBSConst;
    }
    public static void SetLocationDataGPS(string localName)
    {
        LBSConst = localName;
        YanhuaMMO.Util.CallMethod("LBSManager", "OnLocaltionOK");
    }

    public void LocationDataGPS(LuaFunction callback) {
        StartCoroutine(StartLocation());
    }

    public IEnumerator StartLocation()
    {
        Debug.Log("Input.location.isEnabledByUser"+Input.location.isEnabledByUser);
        // First, check if user has location service enabled
        if (!Input.location.isEnabledByUser){
            gameObject.AddComponent<GetLocationData>();
            yield break;
        }
           
        
        // Start service before querying location
        Input.location.Start();
 
        // Wait until service initializes
        int maxWait = 20;
        while (Input.location.status == LocationServiceStatus.Initializing && maxWait > 0)
        {
            yield return new WaitForSeconds(1);
            maxWait--;
        }
 
        // Service didn't initialize in 20 seconds
        if (maxWait < 1)
        {
            print("Timed out");
            Input.location.Stop();
            yield break;
        }
 
        // Connection has failed
        if (Input.location.status == LocationServiceStatus.Failed)
        {
            Debug.Log("Unable to determine device location");
            Input.location.Stop();
            yield break;
        }
        else
        {
            // Access granted and location value could be retrieved
            Debug.Log("StartLocation Location: " + Input.location.lastData.latitude + " " + Input.location.lastData.longitude+"timestamp"+ Input.location.lastData.timestamp);
			StartCoroutine(GetRealLocation(Input.location.lastData.latitude.ToString(), Input.location.lastData.longitude.ToString()));
        }
 
        // Stop service if there is no need to query location updates continuously
        Input.location.Stop();
    }

	public IEnumerator GetRealLocation(string y,string x)
	{
		
		string checkPath=string.Format(FURL,y,x);
		Debug.Log("GetRealLocation:url " + checkPath);
		UnityWebRequest webRequest = UnityWebRequest.Get(checkPath);

        yield return webRequest.SendWebRequest();
		//异常处理，很多博文用了error!=null这是错误的，请看下文其他属性部分
		if (webRequest.isHttpError||webRequest.isNetworkError)
            Debug.Log("webRequest error:"+webRequest.error);
        else 

		{
            Debug.Log("GetRealLocation done: " + webRequest.downloadHandler.text);
 
            if (webRequest.downloadHandler.text.ToLower().Contains("Error".ToLower()) == false)
            {
				/*var req = JsonMapper.ToObject(webRequest.downloadHandler.text);
				var result = req["result"];
				if (result == null) yield break;
				var com = result["addressComponent"];
				if (com == null) yield break;*/
				ResponseBodyComp req = JsonMapper.ToObject<ResponseBodyComp>(webRequest.downloadHandler.text);
				if (req.result == null || req.result.addressComponent == null)
				{
                    SetLocationDataGPS("");
					yield break;
				}
				if (req.result.addressComponent.province == req.result.addressComponent.city)
				{
                    LBSLocation.SetLocationDataGPS(req.result.addressComponent.city);
				}
				else
				{
                    LBSLocation.SetLocationDataGPS(req.result.addressComponent.province);
				}
				//PosAdress=req.result.addressComponent.province+req.result.addressComponent.city+req.result.addressComponent.district;
				//LBSConst = com["province"].ToString();
				// if(callback!=null)
				// {
				// 	callback.Call(PosAdress);
				// 	PosAdress="";
				// }				
				Debug.Log("GetRealLocation location : " + LBSConst);
            }
            else
            {
                Debug.Log( " 局域网，或者虚假连接网络");
            }
        }
    }

}
